<template>
  <div>
    <a-card :bordered="false">
      <a-form
        ref="modifyPriceForm"
        :model="form"
        :style="{ width: '100%' }"
        layout="horizontal"
        auto-label-width
      >
        <div class="base-info-item">
          <h4>活动信息</h4>
          <div class="form-item-view">
            <a-form-item
              field="promotionName"
              label="活动名称"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="form.promotionName"
                allow-clear
                :style="{ width: '260px' }"
                :disabled="disabled"
              />
            </a-form-item>
            <a-form-item field="rangeTime" label="活动时间" :rules="[REQUIRED]">
              <a-range-picker
                v-model="form.rangeTime"
                style="width: 360px; margin-bottom: 20px"
                :disabled="disabled"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
            <a-form-item
              field="description"
              label="活动描述"
              :rules="[REQUIRED]"
            >
              <a-textarea
                v-model="form.description"
                allow-clear
                style="width: 260px"
                :disabled="disabled"
              />
            </a-form-item>
          </div>
          <h4>优惠设置</h4>
          <div class="form-item-view">
            <a-form-item field="fullMoney" label="优惠门槛" :rules="[REQUIRED]">
              <a-input
                v-model="form.fullMoney"
                allow-clear
                :style="{ width: '260px' }"
                :disabled="disabled"
              />
              <span class="describe">消费达到当前金额可以参与优惠</span>
            </a-form-item>
            <a-form-item
              field="discountType"
              label="赠送优惠券"
              :rules="[REQUIRED]"
            >
              <a-radio-group v-model="form.discountType" type="button">
                <a-radio value="fullMinusFlag" :disabled="disabled"
                  >减现金</a-radio
                >
                <a-radio value="fullRateFlag" :disabled="disabled"
                  >打折</a-radio
                >
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-if="form.discountType == 'fullMinusFlag'"
              field="fullMinus"
              label="优惠金额"
              :rules="[REQUIRED]"
            >
              <a-input
                v-model="form.fullMinus"
                allow-clear
                :style="{ width: '260px' }"
                :disabled="disabled"
              />
            </a-form-item>
            <a-form-item
              v-if="form.discountType == 'fullRateFlag'"
              field="fullRate"
              label="优惠折扣"
              :rules="[REQUIRED, VARCHARDECIMAL10]"
            >
              <a-input
                v-model="form.fullRate"
                allow-clear
                :style="{ width: '260px' }"
                :disabled="disabled"
              />
              <span class="describe">优惠折扣为0-10之间数字，可有一位小数</span>
            </a-form-item>
            <a-form-item field="fullRate" label="额外赠送">
              <a-checkbox v-model="form.freeFreightFlag" :disabled="disabled"
                >免邮费</a-checkbox
              >&nbsp;
              <a-checkbox v-model="form.couponFlag" :disabled="disabled"
                >送优惠券</a-checkbox
              >&nbsp;
              <a-checkbox v-model="form.giftFlag" :disabled="disabled"
                >送赠品</a-checkbox
              >&nbsp;
              <a-checkbox v-model="form.pointFlag" :disabled="disabled"
                >送积分</a-checkbox
              >&nbsp;
            </a-form-item>
            <a-form-item
              v-if="form.couponFlag"
              field="couponId"
              label="赠送优惠券"
            >
              <a-select
                v-model="form.couponId"
                allow-search
                style="width: 280px"
                :disabled="form.promotionStatus != 'NEW'"
                @search="handleSearchcoupon"
              >
                <a-option
                  v-for="item in couponList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.couponName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="form.giftFlag" field="giftId" label="赠品">
              <a-select
                v-model="form.giftId"
                allow-search
                style="width: 280px"
                :disabled="form.promotionStatus != 'NEW'"
                @search="handleSearchgift"
              >
                <a-option
                  v-for="item in giftList"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.goodsName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="form.pointFlag" field="point" label="赠积分">
              <a-input-number
                v-model="form.points"
                :style="{ width: '260px' }"
                :disabled="disabled"
              />
            </a-form-item>
            <a-form-item field="scopeType" label="使用范围" :rules="[REQUIRED]">
              <a-radio-group v-model="form.scopeType" type="button">
                <a-radio value="ALL" :disabled="disabled">全品类</a-radio>
                <a-radio value="PORTION_GOODS" :disabled="disabled"
                  >指定商品</a-radio
                >
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-if="form.scopeType == 'PORTION_GOODS'"
              style="width: 100%"
            >
              <div v-if="form.promotionStatus == 'NEW'" style="display: flex">
                <div style="display: flex; margin-bottom: 10px">
                  <a-button
                    :disabled="disabled"
                    type="outline"
                    @click="openSkuList"
                    >选择商品</a-button
                  >
                  <a-button
                    :disabled="disabled"
                    style="margin-left: 10px"
                    type="outline"
                    status="danger"
                    @click="delSelectGoods"
                    >批量删除</a-button
                  >
                </div>
              </div>
            </a-form-item>
            <a-form-item v-if="form.scopeType == 'PORTION_GOODS'">
              <a-table
                v-model:selectedKeys="selectedKeys"
                :columns="columns"
                :data="promotionGoodsList"
                :row-selection="rowSelection"
                row-key="skuId"
                :pagination="false"
                :style="{ width: '100%' }"
              >
                <template #Optiona="{ rowIndex }">
                  <a-button
                    type="text"
                    status="danger"
                    :disabled="disabled"
                    @click="delGoods(rowIndex)"
                    >删除</a-button
                  >
                </template>
              </a-table>

              <!--<tablePage :columns="columns" :checkbox="true"   @selectTableChange="selectTableChange" :dataList="promotionGoodsList" :methods="sortMethods">               -->
              <!--&lt;!&ndash; <template #goodsName="{ record }">-->
              <!--<div>-->
              <!--<a class="mr_10" @click="linkTo(record.goodsId, record.skuId)">{{-->
              <!--record.goodsName-->
              <!--}}</a>-->
              <!--</div>-->
              <!--</template> &ndash;&gt;-->
              <!--<template #delete="{ rowIndex }" >-->
              <!--<a-button :disabled="form.promotionStatus != 'NEW' && !!route.query.id" @click="delGoods(rowIndex)">删除</a-button>-->
              <!--</template>  -->
              <!--</tablePage>-->
            </a-form-item>
            <div>
              <a-button
                style="margin-right: 5px"
                @click="router.push({ name: 'full-discount' })"
                >返回</a-button
              >
              <a-button
                type="primary"
                :disabled="disabled"
                @click="handleSubmit"
                >提交</a-button
              >
            </div>
          </div>
        </div>
      </a-form>
    </a-card>
    <skuselect
      ref="skuSelect"
      :goods-or-sku="true"
      :default-goods-selected-list="promotionGoodsList"
      @change="changSkuList"
    ></skuselect>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import tablePage from '@/components/table-pages/index.vue';
  import skuselect from '@/components/goods-sku-selector/index.vue';
  import {
    getShopCouponList,
    getFullDiscountById,
    newFullDiscount,
    editFullDiscount,
  } from '@/api/promotion';
  import { getGoodsSkuListDataSeller } from '@/api/goods';
  import { dayFormatHHssMM } from '@/utils/filters';
  import { ColumnsDataRule, MethodsRule } from '@/types/global';
  import { Message } from '@arco-design/web-vue';
  import useCurrentInstance from '@/hooks/useCurrentInstance';
  import { REQUIRED, VARCHARDECIMAL10 } from '@/utils/validator';

  const modifyPriceForm = ref();
  //  获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const route = useRoute();
  const router = useRouter();
  const disabled = ref(route.query.onlyView) as any;
  const skuSelect = ref(null) as any; // 商品选择器
  const promotionGoodsList = ref([]) as any; // 活动商品列表
  const form = ref<any>({
    promotionName: '',
    rangeTime: '',
    description: '',
    fullMoney: '',
    discountType: 'fullMinusFlag',
    fullMinus: '',
    fullRate: '',
    freeFreightFlag: false,
    couponFlag: false,
    giftFlag: false,
    pointFlag: false,
    promotionStatus: 'NEW',
    couponId: '',
    giftId: '',
    point: 0,
    scopeType: 'ALL',
    promotionGoodsList: [],
  });
  const columns = [
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      currency: true,
    },
    {
      title: '库存',
      dataIndex: 'quantity',
    },
    {
      title: '操作',
      slotName: 'Optiona',
    },
  ];
  const sortMethods: MethodsRule = {
    title: '操作',
    width: 250,
    fixed: 'right',
    methods: [
      {
        title: '删除',
        callback: 'delete',
        slot: true,
        slotTemplate: 'delete',
      },
    ],
  };

  // 表格的行选择器配置
  const rowSelection = reactive<any>({
    type: 'checkbox',
    showCheckedAll: true,
    // selectedRowKeys: [],
    onlyCurrent: true,
  });
  const selectedKeys = ref([]);

  const couponList = ref([]) as any; // 优惠券列表
  const giftList = ref([]) as any; // 赠品列表
  // 获取活动详情
  const getDetail = async () => {
    const res = await getFullDiscountById(route.query.id);
    if (res.data.success) {
      const data = res.data.result;
      if (data.scopeType === 'ALL') {
        data.promotionGoodsList = [];
      }

      if (data.fullMinusFlag) {
        data.discountType = 'fullMinusFlag';
        delete data.fullMinusFlag;
      } else {
        data.discountType = 'fullRateFlag';
        delete data.fullRateFlag;
      }
      data.rangeTime = [];
      data.rangeTime.push(data.startTime, data.endTime);
      form.value = data;
      promotionGoodsList.value = data.promotionGoodsList;
    }
  };
  const getCouponList = async (val?: any) => {
    const params = {
      pageSize: 10,
      pageNumber: 0,
      getType: 'ACTIVITY',
      storeId: '',
      couponName: val,
      promotionStatus: 'START',
    };
    const res = await getShopCouponList(params);
    if (res.data.success) {
      couponList.value = res.data.result.records;
    }
  };
  const getGiftList = async (val?: any) => {
    // 赠品列表
    const params = {
      pageSize: 10,
      pageNumber: 1,
      id: form.value.giftId ? null : form.value.giftId,
      goodsName: val === form.value.giftId ? null : val,
      marketEnable: 'UPPER',
      authFlag: 'PASS',
    };
    const res = await getGoodsSkuListDataSeller(params);
    if (res.data.success) {
      giftList.value = res.data.result.records;
    }
  };
  // 赠送优惠券搜索
  const handleSearchcoupon = (val: any) => {
    getCouponList(val);
  };
  // 赠品搜索
  const handleSearchgift = (val: any) => {
    getGiftList(val);
  };
  // 返回上一页
  const routerpreviousPage = () => {
    router.push({ name: 'full-discount' });
  };
  // 提交
  const handleSubmit = async () => {
    const auth = await modifyPriceForm.value?.validate();
    if (!auth) {
      // form.promotionGoodsList =  promotionGoodsList.value
      const params = JSON.parse(JSON.stringify(form.value));
      params.promotionGoodsList = promotionGoodsList.value;
      params.startTime = form.value.rangeTime[0];
      params.endTime = form.value.rangeTime[1];
      if (
        params.scopeType == 'PORTION_GOODS' &&
        (!params.promotionGoodsList || params.promotionGoodsList.length == 0)
      ) {
        Message.warning('请选择指定商品');
        return;
      }
      if (params.scopeType == 'ALL') {
        delete params.promotionGoodsList;
        params.number = -1;
      } else {
        const scopeId: any = [];
        params.number = 1;
        params.promotionGoodsList.forEach((e: any) => {
          e.startTime = params.startTime;
          e.endTime = params.endTime;
          scopeId.push(e.skuId);
        });
        params.scopeId = scopeId.toString();
      }
      if (params.discountType == 'fullMinusFlag') {
        params.fullMinusFlag = true;
      } else {
        params.fullRateFlag = true;
      }
      delete params.rangeTime;
      if (!route.query.id) {
        delete params.id;
        newFullDiscount(params).then((res: any) => {
          if (res && res.data && res.data.success) {
            Message.success('添加活动成功');
            routerpreviousPage();
          }
        });
      } else {
        // 编辑
        delete params.updateTime;
        editFullDiscount(params).then((res: any) => {
          if (res.data.success) {
            Message.success('编辑活动成功');
            routerpreviousPage();
          }
        });
      }
    }
  };

  // 选择商品
  const openSkuList = () => {
    skuSelect.value.modalData.visible = true;
  };
  // 选择的商品
  const changSkuList = (val: any) => {
    const list: any = [];
    val.forEach((e: any) => {
      const obj = {
        settlementPrice: e.settlementPrice || 0,
        pointsGoodsCategoryId: e.pointsGoodsCategoryId || 0,
        pointsGoodsCategoryName: e.pointsGoodsCategoryName || '',
        activeStock: e.activeStock || 0,
        points: e.points || 0,
        skuId: e.id,
        goodsId: e.goodsId,
        originalPrice: e.price || 0,
        thumbnail: e.thumbnail || '',
        goodsName: e.goodsName || '',
        quantity: e.quantity || '',
        storeName: e.storeName || '',
        price: e.price || '',
        id: e.id,
      };
      list.push(obj);
    });
    promotionGoodsList.value = list;
  };
  // 删除商品
  const delGoods = (index: any) => {
    promotionGoodsList.value.splice(index, 1);
  };
  // 多选删除商品
  const delSelectGoods = () => {
    if (selectedKeys.value.length === 0) {
      Message.warning('您还未选择要删除的数据！');
      return;
    }
    const res = JSON.parse(JSON.stringify(selectedKeys.value));

    modal.confirm({
      title: '确认删除',
      content: '您确认要删除所选商品吗?',
      alignCenter: false,
      onOk: () => {
        promotionGoodsList.value = promotionGoodsList.value.filter(
          (item: any) => {
            return !res.includes(item.skuId);
          }
        );
        selectedKeys.value = [];
      },
    });
  };
  onMounted(async () => {
    if (route.query.id) {
      getDetail();
    }
    await getCouponList();
    await getGiftList();
  });
</script>

<style lang="less" scoped>
  h4 {
    margin-bottom: 10px;
    padding: 0 10px;
    border: 1px solid #ddd;
    background-color: #f8f8f8;
    font-weight: bold;
    color: #333;
    font-size: 14px;
    line-height: 40px;
    text-align: left;
  }

  .describe {
    font-size: 12px;
    margin-left: 10px;
    color: #999;
  }
</style>
